<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>七鱼AI API测试页面</title>
    <style>
      body {
        font-family: "PingFang SC", "Microsoft YaHei", sans-serif;
        line-height: 1.6;
        color: #333;
        max-width: 1000px;
        margin: 0 auto;
        padding: 20px;
        background-color: #f5f5f5;
      }
      h1 {
        color: #1a73e8;
        text-align: center;
        margin-bottom: 30px;
      }
      .container {
        display: flex;
        gap: 20px;
      }
      .panel {
        background: white;
        border-radius: 8px;
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        padding: 20px;
        flex: 1;
      }
      .chat-container {
        flex: 2;
      }
      .form-group {
        margin-bottom: 15px;
      }
      label {
        display: block;
        margin-bottom: 5px;
        font-weight: bold;
      }
      select,
      input,
      textarea,
      button {
        width: 100%;
        padding: 10px;
        border: 1px solid #ddd;
        border-radius: 4px;
        font-size: 14px;
      }
      button {
        background-color: #1a73e8;
        color: white;
        border: none;
        cursor: pointer;
        font-weight: bold;
        transition: background-color 0.3s;
      }
      button:hover {
        background-color: #155db1;
      }
      button:disabled {
        background-color: #9aa0a6;
        cursor: not-allowed;
      }
      .messages {
        height: 400px;
        overflow-y: auto;
        border: 1px solid #ddd;
        border-radius: 4px;
        padding: 10px;
        background-color: #f9f9f9;
        margin-bottom: 15px;
      }
      .message {
        margin-bottom: 10px;
        padding: 10px;
        border-radius: 4px;
      }
      .user-message {
        background-color: #e3f2fd;
        margin-left: 20px;
        border-left: 4px solid #1a73e8;
      }
      .ai-message {
        background-color: #f1f3f4;
        margin-right: 20px;
        border-left: 4px solid #34a853;
      }
      .system-message {
        background-color: #fce8e6;
        border-left: 4px solid #ea4335;
        font-style: italic;
      }
      .status {
        text-align: center;
        margin-top: 10px;
        font-style: italic;
        color: #5f6368;
      }
      .models-list {
        list-style-type: none;
        padding: 0;
      }
      .models-list li {
        padding: 10px;
        border-bottom: 1px solid #eee;
      }
      .models-list li:last-child {
        border-bottom: none;
      }
      .model-name {
        font-weight: bold;
        color: #1a73e8;
      }
      .model-id {
        color: #5f6368;
        font-size: 0.9em;
      }
      .model-description {
        margin-top: 5px;
        font-size: 0.9em;
      }
      pre {
        background-color: #f1f3f4;
        padding: 10px;
        border-radius: 4px;
        overflow-x: auto;
      }
      .loading {
        display: inline-block;
        width: 20px;
        height: 20px;
        border: 3px solid rgba(255, 255, 255, 0.3);
        border-radius: 50%;
        border-top-color: #fff;
        animation: spin 1s ease-in-out infinite;
      }
      @keyframes spin {
        to {
          transform: rotate(360deg);
        }
      }
    </style>
  </head>
  <body>
    <h1>七鱼AI API测试页面</h1>

    <div class="container">
      <div class="panel">
        <h2>可用模型</h2>
        <div id="models-container">
          <p>加载中...</p>
        </div>

        <h2>API状态</h2>
        <div id="health-status">
          <p>检查中...</p>
        </div>
      </div>

      <div class="panel chat-container">
        <h2>聊天测试</h2>
        <div class="form-group">
          <label for="model-select">选择模型:</label>
          <select id="model-select">
            <option value="">加载中...</option>
          </select>
        </div>

        <div class="messages" id="messages">
          <div class="message system-message">
            欢迎使用七鱼AI API测试页面。请选择一个模型并开始对话。
          </div>
        </div>

        <div class="form-group">
          <label for="message-input">输入消息:</label>
          <textarea
            id="message-input"
            rows="3"
            placeholder="在这里输入你的问题..."
          ></textarea>
        </div>

        <div class="form-group">
          <button id="send-button">发送</button>
        </div>

        <div class="form-group">
          <label>参数设置:</label>
          <div style="display: flex; gap: 10px">
            <div style="flex: 1">
              <label for="temperature">Temperature:</label>
              <input
                type="range"
                id="temperature"
                min="0"
                max="1"
                step="0.1"
                value="0.7"
              />
              <span id="temperature-value">0.7</span>
            </div>
            <div style="flex: 1">
              <label for="top-p">Top P:</label>
              <input
                type="range"
                id="top-p"
                min="0"
                max="1"
                step="0.1"
                value="0.8"
              />
              <span id="top-p-value">0.8</span>
            </div>
          </div>
        </div>

        <div class="status" id="status"></div>
      </div>
    </div>

    <script>
      // 基础URL
      const API_BASE_URL = window.location.origin;

      // DOM元素
      const modelSelect = document.getElementById("model-select");
      const messagesContainer = document.getElementById("messages");
      const messageInput = document.getElementById("message-input");
      const sendButton = document.getElementById("send-button");
      const statusElement = document.getElementById("status");
      const modelsContainer = document.getElementById("models-container");
      const healthStatus = document.getElementById("health-status");
      const temperatureSlider = document.getElementById("temperature");
      const temperatureValue = document.getElementById("temperature-value");
      const topPSlider = document.getElementById("top-p");
      const topPValue = document.getElementById("top-p-value");

      // 消息历史
      let messageHistory = [];

      // 初始化
      async function init() {
        await checkHealth();
        await loadModels();

        // 事件监听器
        sendButton.addEventListener("click", sendMessage);
        messageInput.addEventListener("keydown", (e) => {
          if (e.key === "Enter" && !e.shiftKey) {
            e.preventDefault();
            sendMessage();
          }
        });

        temperatureSlider.addEventListener("input", () => {
          temperatureValue.textContent = temperatureSlider.value;
        });

        topPSlider.addEventListener("input", () => {
          topPValue.textContent = topPSlider.value;
        });
      }

      // 检查API健康状态
      async function checkHealth() {
        try {
          const response = await fetch(`${API_BASE_URL}/api/health`);
          const data = await response.json();

          if (data.success) {
            healthStatus.innerHTML = `
            <div style="color: #34a853; font-weight: bold;">
              <span>✓ API正常运行</span>
            </div>
            <div style="margin-top: 10px;">
              <small>${data.message}</small>
            </div>
            <div style="margin-top: 5px;">
              <small>更新时间: ${new Date(
                data.timestamp
              ).toLocaleString()}</small>
            </div>
          `;
          } else {
            healthStatus.innerHTML = `
            <div style="color: #ea4335; font-weight: bold;">
              <span>✗ API异常</span>
            </div>
            <div style="margin-top: 10px;">
              <small>${data.message}</small>
            </div>
          `;
          }
        } catch (error) {
          healthStatus.innerHTML = `
          <div style="color: #ea4335; font-weight: bold;">
            <span>✗ 无法连接到API</span>
          </div>
          <div style="margin-top: 10px;">
            <small>${error.message}</small>
          </div>
        `;
        }
      }

      // 加载可用模型
      async function loadModels() {
        try {
          const response = await fetch(`${API_BASE_URL}/api/models`);
          const data = await response.json();

          if (data.success && data.data.length > 0) {
            // 更新模型选择下拉框
            modelSelect.innerHTML = "";
            data.data.forEach((model) => {
              const option = document.createElement("option");
              option.value = model.id;
              option.textContent = model.name;
              modelSelect.appendChild(option);
            });

            // 更新模型列表
            modelsContainer.innerHTML = `
            <ul class="models-list">
              ${data.data
                .map(
                  (model) => `
                <li>
                  <div class="model-name">${model.name}</div>
                  <div class="model-id">ID: ${model.id}</div>
                  <div class="model-description">${model.description}</div>
                </li>
              `
                )
                .join("")}
            </ul>
          `;
          } else {
            modelsContainer.innerHTML = "<p>无法加载模型列表</p>";
            modelSelect.innerHTML = '<option value="">无可用模型</option>';
          }
        } catch (error) {
          modelsContainer.innerHTML = `<p>加载模型失败: ${error.message}</p>`;
          modelSelect.innerHTML = '<option value="">加载失败</option>';
        }
      }

      // 发送消息
      async function sendMessage() {
        const message = messageInput.value.trim();
        const selectedModel = modelSelect.value;

        if (!message) {
          return;
        }

        if (!selectedModel) {
          addMessage("system", "请先选择一个模型");
          return;
        }

        // 添加用户消息到界面
        addMessage("user", message);

        // 清空输入框
        messageInput.value = "";

        // 更新消息历史
        messageHistory.push({
          role: "user",
          content: message,
        });

        // 禁用发送按钮
        sendButton.disabled = true;
        sendButton.innerHTML = '<span class="loading"></span> 发送中...';

        // 更新状态
        statusElement.textContent = "正在等待AI响应...";

        try {
          // 获取参数值
          const temperature = parseFloat(temperatureSlider.value);
          const topP = parseFloat(topPSlider.value);

          // 发送请求
          const response = await fetch(`${API_BASE_URL}/api/chat`, {
            method: "POST",
            headers: {
              "Content-Type": "application/json",
            },
            body: JSON.stringify({
              model: selectedModel,
              messages: messageHistory,
              temperature,
              top_p: topP,
            }),
          });

          const data = await response.json();

          if (data.success) {
            // 添加AI响应到界面
            const aiMessage = data.data.result;
            addMessage("ai", aiMessage);

            // 更新消息历史
            messageHistory.push({
              role: "assistant",
              content: aiMessage,
            });

            // 更新状态
            statusElement.textContent = `完成 (用时: ${
              data.data.usage?.total_tokens || "N/A"
            } tokens)`;
          } else {
            // 显示错误
            addMessage("system", `错误: ${data.message}`);
            statusElement.textContent = "请求失败";
          }
        } catch (error) {
          // 显示错误
          addMessage("system", `错误: ${error.message}`);
          statusElement.textContent = "请求失败";
        } finally {
          // 恢复发送按钮
          sendButton.disabled = false;
          sendButton.textContent = "发送";
        }
      }

      // 添加消息到界面
      function addMessage(role, content) {
        const messageElement = document.createElement("div");
        messageElement.classList.add("message");

        if (role === "user") {
          messageElement.classList.add("user-message");
          messageElement.textContent = content;
        } else if (role === "ai") {
          messageElement.classList.add("ai-message");
          messageElement.textContent = content;
        } else {
          messageElement.classList.add("system-message");
          messageElement.textContent = content;
        }

        messagesContainer.appendChild(messageElement);

        // 滚动到底部
        messagesContainer.scrollTop = messagesContainer.scrollHeight;
      }

      // 初始化
      init();
    </script>
  </body>
</html>
